<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form name="f1">
      <p>
        Hobby
        <input type="checkbox" checked name="hobby" value="css" /> CSS
        <input type="checkbox" name="hobby" value="html" /> HTML
        <input type="checkbox" checked name="hobby" value="js" /> JS
        <input type="checkbox" name="hobby" value="sass" /> SASS
      </p>
      <p>
        <button type="button" name="submitBtn">提交</button>
      </p>
    </form>
    <script>
      const form = document.f1;
      form.submitBtn.onclick = function () {
        // 只返回选中项
        const genderArr = [...form.querySelectorAll('[name="hobby"]:checked')];
        // 获取选中项的value
        console.log(
          genderArr.map((el) => {
            return el.value;
          })
        );

        // 遍历 name="hobby"
        [...form.hobby].forEach((el) => {
          // 判断值是否存在选中数组中，存在返回true否则返回false
          const r = ["js", "html"].includes(el.value);
          // 设置
          el.checked = r;
        });
      };
    </script>
  </body>
</html>
